import 'dart:async';
import 'dart:developer';
import 'dart:io';

import 'package:ceramics/model/ab_singleton.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_uuid.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/foundation.dart';
import 'package:package_info_plus/package_info_plus.dart';

import 'ab_const_url.dart';

/// 打点请求头key统一传参
class HBLogHeadersKey{

  static const String logData = "data";
  static const String logLogType = "log_type";
  static const String logSubtype = "subtype";
  static const String logBehavior = "behavior";
  static const String logDeviceId = "device-id";
  static const String logAndroidId = "android_id";
  static const String logUserId = "user_id";
  static const String logPkg = "pkg";
  static const String logChnId = "chn_id";
  static const String logVer = "ver";
  static const String logPlatform = "platform";
  static const String logModel = "model";
  static const String logPVer = "p_ver";
  static const String logLanId = "lan_id";
  static const String logSecId = "sec_id";
  static const String logUtmSource = "utm_source";
  static const String logAfAdgroupId = "af_adgroup_id";
  static const String logAfAdset = "af_adset";
  static const String logAfAdsetId = "af_adset_id";
  static const String logAfStatus = "af_status";
  static const String logAfAgency = "af_agency";
  static const String logAfChannel = "af_channel";
  static const String logAfCampaign = "campaign";
  static const String logAfCampaignId = "campaign_id";
  static const String logCountry = "country";
  static const String logsysLan = "sys_lan";
}

/// 打点中所有涉及到的页面KEY
class LogPages {
  // key值（字符串）参考下面的埋点事件
}

class LogPvManger {
  LogPvManger._();

  static const String _event = 'event';
  static const String _tm = 'tm';
  static const String _page = 'page';
  static const String _subPage = 'subPage';
  static const String _terPage = 'terPage';
  static const String _broadcasterId = 'broadcasterId';
  static const String _duration = 'duration';

  static void stat({
    String? page,
    String? subPage,
    String? terPage,
    String? broadcasterId,
  }) {
    var map = <String, dynamic>{};
    // ⚠️page传入下方的埋点事件page值
    if (page != null) {
      map[_page] = page;
    }
    if (subPage != null) {
      map[_subPage] = subPage;
    }
    if (terPage != null) {
      map[_terPage] = terPage;
    }
    if (broadcasterId != null) {
      map[_broadcasterId] = broadcasterId;
    }
    map[_duration] = 0;
    map[_event] = 'pv';
    map[_tm] = DateTime.now().millisecondsSinceEpoch;

    if (kDebugMode) {
      log('$map', name: 'LogPvMgr');
    }
    LogManger().putLog(LogType.globalBehavior, map);
  }
}

/// 打点类型
enum LogType {
  globalBehavior('event', 'global_behavior', 'event'),
  clickEvent("event", "click", "event");

  final String logType;
  final String subType;
  final String behavior;

  const LogType(this.logType, this.subType, this.behavior);
}

// 打点管理
class LogManger {
  static final LogManger _instance = LogManger._internal();
  factory LogManger() {
    return _instance;
  }
  LogManger._internal();

  static const String tag = "LogManger"; // 日志标签
  static const int limitSize = 20; // 打点任务最多缓存长度
  static int _serialId = 0;
  // 每次启动App该值会修改
  static String launcherId = DateTime.now().millisecondsSinceEpoch.toString();
  final List<Map<String, dynamic>> cacheList = [];
  bool _isWaitingForSend = false; // 是否需要延迟上报

  /// 上报日志
  void putLog(LogType logType, Map<String, dynamic>? event) async {
    if (logType.logType.isEmpty ||
        logType.subType.isEmpty ||
        logType.behavior.isEmpty ||
        event == null ||
        event.isEmpty) {
      return;
    }
    Map<String, dynamic> itemData = await _buildItemData(
        logType.logType, logType.subType, logType.behavior, event);
    cacheList.insert(0, itemData);
    sendDelayed();
  }

  /// 延时发送日志
  void sendDelayed() {
    if (_isWaitingForSend) {
      return;
    }
    _isWaitingForSend = true;
    Timer(const Duration(milliseconds: 2000), () {
      _isWaitingForSend = false;
      sendLog(false);
    });
  }

  /// 发日志打点
  void sendLog(bool forceUploadAll) {
    try {
      List<Map<String, dynamic>> sendList = [];
      if (cacheList.isEmpty) {
        return;
      } else if (cacheList.length >= limitSize && !forceUploadAll) {
        sendList.addAll(cacheList.sublist(0, limitSize));
        cacheList.removeRange(0, limitSize);
      } else {
        sendList.addAll(cacheList);
        cacheList.clear();
      }
      _doUpload(sendList, true);
    } catch (e) {
      if (kDebugMode) {
        print(e);
      }
    }
  }

  /// 立马发送日志
  void putLogRightNow(LogType logType, Map<String, dynamic>? event) async {
    if (logType.logType.isEmpty ||
        logType.subType.isEmpty ||
        logType.behavior.isEmpty ||
        event == null ||
        event.isEmpty) {
      return;
    }
    Map<String, dynamic> itemData = await _buildItemData(
        logType.logType, logType.subType, logType.behavior, event);
    List<Map<String, dynamic>> list = [];
    list.add(itemData);

    _doUpload(list, false);
  }

  /// 执行上传
  Future<void> _doUpload(
      List<Map<String, dynamic>> sendList, bool isContinue) async {
    await api.post(ABURLs.logURL,parameter: sendList,showLoading: false);
    if (isContinue) {
      sendDelayed();
    }
  }

  Future<Map<String, dynamic>> _buildItemData(String logType, String subType,
      String behavior, Map<String, dynamic>? event) async {
    String platform = '';
    String model = '';
    var deviceInfo = DeviceInfoPlugin();
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    var iosInfo = await deviceInfo.iosInfo;
    if (Platform.isAndroid) {
      platform = 'Android';
      model = await deviceInfo.androidInfo.then((value) => value.model);
    } else if (Platform.isIOS) {
      platform = 'iOS';
      model = await deviceInfo.iosInfo.then((value) => value.model);
    }
    Map<String, dynamic> itemData = {};
    itemData[HBLogHeadersKey.logData] = [event];
    itemData[HBLogHeadersKey.logLogType] = 'event';
    itemData[HBLogHeadersKey.logSubtype] = 'global_behavior';
    itemData[HBLogHeadersKey.logBehavior] = 'event';
    itemData[HBLogHeadersKey.logDeviceId] = await getUUID();
    itemData[HBLogHeadersKey.logUserId] = ABSingleton.user?.userId ?? '';
    itemData[HBLogHeadersKey.logPkg] = packageInfo.packageName;
    itemData[HBLogHeadersKey.logChnId] = '';
    itemData[HBLogHeadersKey.logVer] = packageInfo.version;
    itemData[HBLogHeadersKey.logPlatform] = platform;
    itemData[HBLogHeadersKey.logModel] = model;
    itemData[HBLogHeadersKey.logPVer] = packageInfo.buildNumber;
    itemData[HBLogHeadersKey.logLanId] = launcherId;
    itemData[HBLogHeadersKey.logSecId] = _serialId++;
    itemData[HBLogHeadersKey.logsysLan] = iosInfo.localizedModel;
    itemData[HBLogHeadersKey.logCountry] = ABSingleton.user?.country;
    itemData["tm"] = DateTime.now().millisecondsSinceEpoch;
    return itemData;
  }
}